/*
 * LayoutAdditive.java
 *
 * Copyright (c) 2007 Aris Bartee
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
* 
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
* 
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
 * Created on July 9, 2007, 11:13 PM
 */

package afterburner.jsp.fuel;

import java.lang.reflect.Method;

import javax.servlet.ServletContext;

import afterburner.jsp.Base;
import afterburner.jsp.JSP;
import afterburner.jsp.annotations.LayoutTemplate;
import afterburner.jsp.annotations.NoLayout;
import java.text.MessageFormat;
/**
 *
 * @author arisbartee
 */
public class LayoutAdditive implements FuelAdditive{
	private String layoutConflict = "{0} can not have both a defined Layout and a No Layout setting.";
	public void contextInitialized(ServletContext context){}
    
    public void contextDestroyed(ServletContext context){}
    
    public void preJSP(Base baseJsp){
		JSP jsp = (JSP)baseJsp;
		jsp.setLayoutPath(null);
		if(jsp.getClass().getSuperclass().isAnnotationPresent(LayoutTemplate.class)){
			LayoutTemplate lt = jsp.getClass().getSuperclass().getAnnotation(LayoutTemplate.class);
			jsp.setLayoutPath(lt.value());
		}
		String action = jsp.getAction();
		try {
			if(action != null){
				Method method = jsp.getClass().getMethod(action,new Class[0]);
				LayoutTemplate lt = method.getAnnotation(LayoutTemplate.class);
				NoLayout nl = method.getAnnotation(NoLayout.class);
				if(lt != null && nl != null){
					throw new RuntimeException(MessageFormat.format(layoutConflict, method.getName()));
				} else if(nl != null){
					jsp.setLayoutPath(null);
				} else if (lt != null){
					jsp.setLayoutPath(lt.value());
				}
			}
		}catch(NoSuchMethodException e){
			baseJsp.getServletConfig().getServletContext().log(e.getMessage());
		}
		
	}
    public void postJSP(Base baseJsp){
    	JSP jsp = (JSP)baseJsp;
    	jsp.setLayoutPath(null);
    }
}